import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_web_view/repository/favourites_repository.dart';
import 'package:flutter_web_view/util/share_util.dart';

import 'bean/favourites.dart';

/// 我喜欢的列表
class FavouritesPage extends StatefulWidget {
  const FavouritesPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _FavouritesPageState();
  }
}

class _FavouritesPageState extends State<FavouritesPage> {
  /// 我喜欢的数据
  final List<Favourite> _favourites = <Favourite>[];

  EasyRefreshController? _controller;

  /// 下拉刷新
  void _refresh() async {
    _getFavouriteData(() {
      _controller?.finishRefresh(success: true);
    });
  }

  /// 加载更多
  void _loadMore() async {
    _getFavouriteData(() {
      _controller?.finishLoad(noMore: false);
    });
  }

  void _getFavouriteData(Function callback) {
    FavouritesRepository.getAllFavourite().then((list) {
      setState(() {
        _favourites.clear();
        _favourites.addAll(list);
      });
      callback();
    });
  }

  /// 删除我喜欢的
  void _deleteFavourite(Favourite favourite) async {
    var result = await FavouritesRepository.removeFavourite(favourite.url);
    if (result) {
      setState(() {
        _favourites.remove(favourite);
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController();
    _refresh();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
            onPressed: () {
              Navigator.pop(context, null);
            },
            icon: const Icon(Icons.arrow_back)),
        title: const Text("我喜欢的"),
      ),
      body: EasyRefresh(
          header: ClassicalHeader(
            refreshText: "下拉可以刷新",
            refreshReadyText: "松开立即刷新",
            refreshingText: "正在刷新数据中...",
            refreshedText: "刷新完成",
            infoText: "上次更新 %T",
          ),
          footer: ClassicalFooter(),
          controller: _controller,
          onRefresh: () async {
            _refresh();
          },
          onLoad: null,
          child: ListView.separated(
              itemCount: _favourites.length,
              separatorBuilder: (context, index) {
                return const Divider(
                  height: 1,
                  indent: 0,
                  color: Color(0xFFDDDDDD),
                );
              },
              itemBuilder: (BuildContext context, int index) {
                return Slidable(
                    key: ValueKey("$index"),
                    direction: Axis.horizontal,
                    endActionPane: ActionPane(
                      motion: const ScrollMotion(),
                      children: [
                        SlidableAction(
                          padding: const EdgeInsets.only(top: 10, bottom: 10),
                          backgroundColor: Colors.blue,
                          foregroundColor: Colors.white,
                          icon: Icons.share,
                          label: '分享',
                          onPressed: (BuildContext context) {
                            var favourite = _favourites[index];
                            ShareUtil.shareText(
                                '${favourite.title}\n${favourite.url}');
                          },
                        ),
                        SlidableAction(
                          padding: const EdgeInsets.only(top: 10, bottom: 10),
                          backgroundColor: Colors.red,
                          foregroundColor: Colors.white,
                          icon: Icons.delete,
                          label: '删除',
                          onPressed: (BuildContext context) {
                            _deleteFavourite(_favourites[index]);
                          },
                        ),
                      ],
                    ),
                    child: GestureDetector(
                      onTap: () {
                        Navigator.pop(context, _favourites[index]);
                      },
                      child: ListTile(
                        title: Text(
                          _favourites[index].title,
                          style: const TextStyle(
                            color: Colors.black,
                            fontSize: 16,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        subtitle: Container(
                          margin: const EdgeInsets.only(top: 5),
                          child: Text(
                            _favourites[index].url,
                            style: const TextStyle(
                              color: Colors.grey,
                              fontSize: 13,
                              height: 1.5,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ),
                    ));
              })),
    );
  }
}
